<template>
  <a-modal :width="1200" v-model:visible="showDetail" title="确认交货单" title-align="start" :mask-closable="false" @cancel="closedDialog">
    <div class="purchase-order-detail">
      <div class="flex-c bill-info">
        <p style="margin-right: 20px">
          <span>交货单号：</span>
          <span class="highlight">{{ detailInfo.billNo }}</span>
        </p>
        <p style="margin-right: 20px">
          <span>收货仓：</span>
          <span>{{ detailInfo.warehouseName }}（{{ detailInfo.warehouseCode }}）</span>
        </p>
        <p style="margin-right: 20px">
          <span>供应商：</span>
          <span>{{ detailInfo.supplierName }}（{{ detailInfo.supplierCode }}）</span>
        </p>
        <p>
          <span>提交时间：</span>
          <span>{{ $setTime(detailInfo.gmtAcceptSubmit) }}</span>
        </p>
      </div>
      <div class="purchase-detail-order">
        <a-table class="table-two-line show-border-table" ref="tableRef" :data="detailInfo.billItems" :scroll="{ x: '100%', y: '100%' }" size="mini" :pagination="false">
          <template #columns>
            <a-table-column data-index="purchaseNo" title="采购单" :width="130" fixed="left">
              <template #cell="{ record }">
                <p class="highlight">{{ record.purchaseNo }}</p>
              </template>
            </a-table-column>
            <a-table-column data-index="img" title="图片" :width="60" fixed="left">
              <template #cell="{ record }">
                <ImgPopover :src="record.productImg">
                  <template #con>
                    <a-image width="50" height="50" fit="contain" :src="record.productImg" />
                  </template>
                </ImgPopover>
              </template>
            </a-table-column>
            <a-table-column data-index="sku" title="SKU" :width="140" fixed="left">
              <template #cell="{ record }">
                <p>{{ record.sku }}</p>
                <p>{{ getProductSpecs(record) }}</p>
              </template>
            </a-table-column>
            <a-table-column data-index="price" title="单价" :width="120">
              <template #cell="{ record }">
                <p>材质：￥{{ record.materialPrice }}</p>
                <p>产品：￥{{ record.productPrice }}</p>
                <p>工费：￥{{ record.laborPrice }}</p>
              </template>
            </a-table-column>
            <a-table-column data-index="deliveryAmt" title="交货数量" :width="70" />
            <a-table-column data-index="materialWeight" title="交货材质重量(g)" :width="110" />
            <a-table-column data-index="deliveryRealAmt" title="实际签收数量" :width="110">
              <template #cell="{ record, rowIndex }">
                <div class="cell flex-c">
                  <a-input-number :precision="0" :min="0" v-model="record.deliveryRealAmt" style="width: 80px" placeholder="" hide-button />
                  <icon-double-down v-if="rowIndex < detailInfo.billItems.length - 1" class="edit-icon" @click="setGlobal(record, 'deliveryRealAmt')" />
                </div>
              </template>
            </a-table-column>
            <a-table-column data-index="materialRealWeight" title="实收材质重量(g)" :width="120">
              <template #title>
                <a-popover content="实收材质重量=(交货材质重量/交货数量)*实际签收数量">
                  <p>
                    <span>实收材质重量(g)</span>
                    <icon-question-circle />
                  </p>
                </a-popover>
              </template>
              <template #cell="{ record, rowIndex }">
                <div class="cell flex-c">
                  <a-input-number :precision="0" :min="0" v-model="record.materialRealWeight" style="width: 80px" placeholder="" hide-button />
                  <icon-double-down v-if="rowIndex < detailInfo.billItems.length - 1" class="edit-icon" @click="setGlobal(record, 'materialRealWeight')" />
                </div>
              </template>
            </a-table-column>
            <a-table-column data-index="otherAmount" title="其他费用" :width="110">
              <template #title>
                <a-popover content="本次交货产生其他费用">
                  <p>
                    <span>其他费用</span>
                    <icon-question-circle />
                  </p>
                </a-popover>
              </template>
              <template #cell="{ record, rowIndex }">
                <div class="cell flex-c">
                  <a-input-number :precision="0" :min="0" v-model="record.otherAmount" style="width: 80px" placeholder="" hide-button />
                  <icon-double-down v-if="rowIndex < detailInfo.billItems.length - 1" class="edit-icon" @click="setGlobal(record, 'otherAmount')" />
                </div>
              </template>
            </a-table-column>
            <a-table-column title="材质金额" :width="90">
              <template #title>
                <a-popover>
                  <template #content>
                    <p>材质金额：</p>
                    <p>签收前=材质单价*交货材质重量</p>
                    <p>签收后=材质单价*实收材质重量</p>
                  </template>
                  <p>
                    <span>材质金额</span>
                    <icon-question-circle />
                  </p>
                </a-popover>
              </template>
              <template #cell="{ record }">
                <span>￥{{ (Number(record.materialRealWeight || 0) * Number(record.materialPrice || 0)).toFixed(2) }}</span>
              </template>
            </a-table-column>
            <a-table-column title="产品金额" :width="90">
              <template #title>
                <a-popover>
                  <template #content>
                    <p>产品金额：</p>
                    <p>签收前=产品单价*交货数量</p>
                    <p>签收后=产品单价*实际签收数量</p>
                  </template>
                  <p>
                    <span>产品金额</span>
                    <icon-question-circle />
                  </p>
                </a-popover>
              </template>
              <template #cell="{ record }">
                <span>￥{{ (Number(record.deliveryRealAmt || 0) * Number(record.productPrice || 0)).toFixed(2) }}</span>
              </template>
            </a-table-column>
            <a-table-column title="工费" :width="90">
              <template #title>
                <a-popover>
                  <template #content>
                    <p>工费金额：</p>
                    <p>签收前=工费单价*交货数量</p>
                    <p>签收后=工费单价*实际签收数量</p>
                  </template>
                  <p>
                    <span>工费</span>
                    <icon-question-circle />
                  </p>
                </a-popover>
              </template>
              <template #cell="{ record }">
                <span>￥{{ (Number(record.deliveryRealAmt || 0) * Number(record.laborPrice || 0)).toFixed(2) }}</span>
              </template>
            </a-table-column>
            <a-table-column title="合计金额" :width="90">
              <template #title>
                <a-popover>
                  <template #content>
                    <p>合计金额=材质金额+产品金额+工费+其他费用</p>
                  </template>
                  <p>
                    <span>合计金额</span>
                    <icon-question-circle />
                  </p>
                </a-popover>
              </template>
              <template #cell="{ record }">
                <span>￥{{ getTotalAmount(record).toFixed(2) }}</span>
              </template>
            </a-table-column>
            <a-table-column title="税金" :width="90">
              <template #title>
                <a-popover>
                  <template #content>
                    <p>税金=税率*合计金额</p>
                  </template>
                  <p>
                    <span>税金</span>
                    <icon-question-circle />
                  </p>
                </a-popover>
              </template>
              <template #cell="{ record }">
                <span>￥{{ ((getTotalAmount(record) * Number(record.rate || 0)) / 100).toFixed(2) }}</span>
              </template>
            </a-table-column>
            <a-table-column title="单件货值" :width="90">
              <template #title>
                <a-popover>
                  <template #content>
                    <p>单件货值(含税)=（合计金额-税金）/实际签收数量</p>
                    <p>单件货值(不含税)=合计金额/实际签收数量</p>
                  </template>
                  <p>
                    <span>单件货值</span>
                    <icon-question-circle />
                  </p>
                </a-popover>
              </template>
              <template #cell="{ record }">
                <span>￥{{ getTotalValue(record).toFixed(2) }}</span>
              </template>
            </a-table-column>
          </template>
        </a-table>
      </div>
    </div>
    <template #footer>
      <a-space>
        <a-button class="gray-outline" @click="closedDialog">取消</a-button>
        <a-popover v-model:popup-visible="showPoper" trigger="click" @popup-visible-change="rejectMsg = null">
          <template #content>
            <p>请填写拒单理由：</p>
            <a-textarea style="width: 300px; height: 100px" v-model="rejectMsg" placeholder="请输入" allow-clear />
            <div style="text-align: right">
              <a-space>
                <a-button class="gray-outline" size="mini" @click="showPoper = false">取消</a-button>
                <a-button type="primary" size="mini" @click="submitRefuse" :loading="submitLoading">确认</a-button>
              </a-space>
            </div>
          </template>
          <a-button class="gray-outline">拒收</a-button>
        </a-popover>
        <a-button type="primary" @click="submitData()" :loading="submitLoading">确认签收</a-button>
      </a-space>
    </template>
  </a-modal>
</template>

<script lang="ts" setup>
  import { ref } from 'vue'
  import { getDeliveryInfo, refusePurchaseDelivery, signPurchaseDelivery } from '@/api/purchaseApplication'
  import { parseJson } from '@/utils'
  import { Message } from '@arco-design/web-vue'
  const emit = defineEmits(['closed', 'success'])
  const props = defineProps({
    isShow: {
      type: Boolean,
      default: false,
    },
    currentId: {
      type: String,
    },
  })

  const showDetail = ref(props.isShow)
  const detailInfo = ref<any>({})
  const rejectMsg = ref()
  const showPoper = ref(false)
  const submitLoading = ref(false)

  // 关闭
  function closedDialog() {
    showDetail.value = false
    emit('closed')
  }

  // 获取详情
  async function getDetail() {
    if (!props.currentId) return
    const res: any = await getDeliveryInfo({ id: props.currentId })
    detailInfo.value = res?.data || {}
    detailInfo.value.billItems.forEach((item: any) => {
      item.materialRealWeight = item.materialWeight
      item.deliveryRealAmt = item.deliveryAmt
    })
  }
  getDetail()

  // 显示sku规格
  function getProductSpecs(item: any) {
    let productSpecs = item.productSpecs ? parseJson(item.productSpecs, []) : []
    return productSpecs.map((el: any) => el.valueCn)?.join('*') || '--'
  }
  // 拒收
  async function submitRefuse() {
    if (!rejectMsg.value) {
      Message.error('请填写拒收原因！')
      return
    }
    submitLoading.value = true
    const res: any = await refusePurchaseDelivery({
      ids: [props.currentId],
      refuseMsg: rejectMsg.value,
    })
    submitLoading.value = false
    if (res) {
      Message.success('已拒收')
      emit('success')
      closedDialog()
    }
  }
  // 确认
  async function submitData() {
    let signItemParams: Array<any> = []
    let flag = false
    detailInfo.value.billItems.forEach((item: any) => {
      if (!item.deliveryRealAmt) {
        flag = true
      }
      signItemParams.push({
        billId: item.billId,
        id: item.id,
        materialRealWeight: item.materialRealWeight,
        deliveryRealAmt: item.deliveryRealAmt,
        otherAmount: item.otherAmount,
      })
    })
    if (flag) {
      Message.error('实际签收数量必填')
      return
    }
    submitLoading.value = true
    const res: any = await signPurchaseDelivery({ signItemParams })
    submitLoading.value = false
    if (res) {
      Message.success('签收成功')
      emit('success')
      closedDialog()
    }
  }
  //设置全局
  async function setGlobal(item: any, key: string) {
    detailInfo.value.billItems.forEach((el: any) => {
      el[key] = item[key]
    })
  }
  // 获取合计金额
  function getTotalAmount(row: any) {
    let materialAmount = Number(row.materialRealWeight || 0) * Number(row.materialPrice || 0)
    let productAmount = Number(row.deliveryRealAmt || 0) * Number(row.productPrice || 0)
    let laborAmount = Number(row.deliveryRealAmt || 0) * Number(row.laborPrice || 0)
    let otherAmount = Number(row.otherAmount || 0)
    return materialAmount + productAmount + laborAmount + otherAmount
  }
  // 获取单件货值
  function getTotalValue(row: any) {
    let totalAmount = getTotalAmount(row)
    let rateAmount = row.priceType === 0 ? 0 : (totalAmount * Number(row.rate || 0)) / 100
    return row.deliveryRealAmt ? (totalAmount - rateAmount) / row.deliveryRealAmt : 0
  }
</script>

<style lang="less" scoped>
  .purchase-order-detail {
    height: calc(84vh - 160px);
    display: flex;
    flex-direction: column;
    .bill-info {
      padding: 15px 10px;
      background-color: var(--color-neutral-2);
      margin-bottom: 5px;
      border: 1px solid var(--color-neutral-3);
    }
    .purchase-detail-order {
      flex: 1;
      display: flex;
      flex-direction: column;
      overflow: hidden;
    }
    .edit-icon {
      font-size: 16px;
      margin-left: 5px;
      cursor: pointer;
    }
  }
</style>
